package suncertify.service.local;

import suncertify.db.Data;
import suncertify.db.RecordNotFoundException;
import suncertify.db.DuplicateKeyException;
import suncertify.util.Options;
import suncertify.service.Service;
import suncertify.service.ServiceEvent;

import java.util.Map;
import java.util.HashMap;

/**
 * Implementation of Service which is not used network connections at all
 */
public class LocalServiceImpl extends Service {
    private static final Options opts = Options.getInstance();
    private Data data = null;

    /**
     * default constructor
     */
    public LocalServiceImpl() {

    }

    protected String[] read(int id) throws RecordNotFoundException {
        return data.read(id);
    }

    protected void update(Integer id, Long lock, String[] data) throws RecordNotFoundException {
        this.data.update(id, data, lock);
    }

    protected void delete(Integer id, Long lock) throws RecordNotFoundException {
        data.delete(id, lock);
    }

    protected int[] find(String[] criteria) {
        notify(ServiceEvent.FINDING);
        int[] result = data.find(criteria);
        notify(ServiceEvent.FOUND);
        return result;
    }

    protected int create(String[] data) throws DuplicateKeyException {
        return this.data.create(data);
    }

    protected Long lock(Integer id) throws RecordNotFoundException {
        return data.lock(id);
    }

    protected void unlock(int id, Long lock) throws RecordNotFoundException {
        data.unlock(id, lock);
    }

    public boolean isActive() {
        return data != null;
    }

    public void init() {
        try {
            notify(ServiceEvent.INITING);
            data = new Data(opts.get(Options.LOCAL_DB_FILE));
            notify(ServiceEvent.INITED);
        } catch (Exception e) {
            notify(ServiceEvent.INIT_ERROR, e.getMessage());
        }
    }

    @Override
    public void shutdown() {
        
    }

    @Override
    public int getColumnCount() {
        return data.getColumnCount();
    }

    public String getColumnName(int col) {
        return data.getColumnName(col);
    }

    protected void cancelLocking(Integer id) {
        throw new UnsupportedOperationException("local service haven't lock cancelling functionality");
    }

}
